<template>
  <router-view/>

</template>

<script>
import {mapState, mapMutations} from "vuex"

export default {
  name: 'App',
  data() {
    return {
      audio: null,
      t1: null,
    }
  },
  computed: {
    ...mapState(["audio_path", "audio_status", "audio_dec", "audio_inc"])
  },
  methods: {
    ...mapMutations(["set_audio_scale", "set_audio_str"]),
    init(mp3) {
      if (this.t1) {
        clearInterval(this.t1)
      }
      this.audio = new Audio();
      this.audio.src = mp3;
      let playPromise;
      playPromise = this.audio.play();

      this.t1 = setInterval(() => {
        this.set_current_time()
      }, 1000)
    },
    play() {
      this.audio.play()
    },
    pause() {
      this.audio.pause()
    },
    set_current_time() {
      let now = this.audio.currentTime
      let all = this.audio.duration
      let scale = Math.floor(now / all * 10000) / 100
      if (scale >= 100) {
        scale = 100
      }
      if (scale <= 0) {
        scale = 0
      }
      let min_now = Math.floor(now / 60)
      let sec_now = parseInt(now) % 60
      if (min_now < 10) {
        min_now = "0" + min_now
      }
      if (sec_now < 10) {
        sec_now = "0" + sec_now
      }
      let now_str = min_now + ":" + sec_now

      let min_all = Math.floor(all / 60)
      let sec_all = parseInt(all) % 60
      if (min_all < 10) {
        min_all = "0" + min_all
      }
      if (sec_all < 10) {
        sec_all = "0" + sec_all
      }
      let all_str = min_all + ":" + sec_all

      let full_str = now_str + "/" + all_str

      this.set_audio_str(full_str)
      this.set_audio_scale(scale)
    }
  },
  watch: {
    audio_path() {
      this.init(this.audio_path)
    },
    audio_status(status) {
      // 监听到地址发生变化，开始播放
      if (status == "play") {
        this.play()
      } else {
        this.pause()
      }
    },
    audio_dec() {
      this.audio.currentTime -= 15
    },
    audio_inc() {
      this.audio.currentTime += 15
    }
  }
}
</script>

<style>
.clear {
  width: 100%;
  height: 1px;
  clear: both;
}
</style>
